package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"os/exec"
	"runtime"
	"server/im"
)

var imStartCmd = &cobra.Command{
	Use:   "im_start",
	Short: "start im",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("im start")
		writePid("im")
		go signalHandle("im", im.Stop)
		im.Start()
		fmt.Println("im ended")
	},
}

var imStopCmd = &cobra.Command{
	Use:   "im_stop",
	Short: "stop im",
	Run: func(cmd *cobra.Command, args []string) {
		pid, err := readPid("im")
		if runtime.GOOS == "windows" {
			fmt.Printf("pid is:%s,", pid)
			return
		} else {
			if err != nil {
				fmt.Println("pid err:", err)
				return
			}
			execCmd := exec.Command("kill", "-15", pid)
			err = execCmd.Run()
			if err != nil {
				fmt.Println("Error executing command:", err)
				return
			}
			fmt.Println("Process killed successfully")
		}
	},
}

func init() {
	rootCmd.AddCommand(imStartCmd)
	rootCmd.AddCommand(imStopCmd)
}
